package com.mlink.ai.chat.service

import android.app.*
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat.startForegroundService
import com.mlink.ai.chat.assistant.robot.R
import com.mlink.ai.chat.ui.activity.SplashActivity
import com.mlink.ai.chat.utils.IntentUtil
import com.mlink.ai.chat.utils.isServiceRunning

class PermanentForegroundService : Service() {

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            runCatching {
                val notification = createNotification()
                startForeground(ONGOING_NOTIFICATION_ID, notification)
            }
        }
        return START_STICKY
    }

    private fun createNotification(): Notification {
        // 创建通知
        val channelId = "permanent_notification"
        val channelName = "Permanent Notification"
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 创建通知渠道
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(channelId, channelName, importance)
            channel.setSound(null, null)
            channel.setShowBadge(false)
            notificationManager.createNotificationChannel(channel)
        }

        val intent = Intent(this, SplashActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, IntentUtil.pendingIntentFlagCompat())
        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_notification_logo)
            .setContentTitle(getString(R.string.permanent_notification_title))
            .setContentText(getString(R.string.permanent_notification_desc))
            .setContentIntent(pendingIntent) // 设置通知点击事件
            .setAutoCancel(false)
            .setOngoing(true)
            .setWhen(0)
            .setPriority(NotificationCompat.PRIORITY_MAX)

        return notificationBuilder.build()
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        // 停止前台服务通知
        stopForeground(true)
    }

    companion object {
        private const val ONGOING_NOTIFICATION_ID = 1

        fun start(context: Context) {
            // 从 Android 12 开始，Google 对前台服务的限制更加严格，无法在后台启动前台服务
            if (!context.isServiceRunning(PermanentForegroundService::class.java) && Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
                val intent = Intent(context, PermanentForegroundService::class.java)
                startForegroundService(context, intent)
            }
        }
    }
}
